package com.xiaobaibai.websocket;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xiaobaibai.service.ITokenService;
import com.xiaobaibai.service.impl.TokenServiceImpl;
import com.xiaobaibai.units.SmsUnit;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.lang.reflect.Field;
import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.ConcurrentHashMap;

@ServerEndpoint("/imserver/{code}")//这个注解代表了多实例模式
@Component//这里的@Component只是为了方便@Autowired注入而已，没有实际意义，也不是单例模式的代表
@Slf4j
public class WebSocketServer {

    /**静态变量，用来记录当前在线连接数。应该把它设计成线程安全的。*/
    private static int onlineCount = 0;
    /**concurrent包的线程安全Set，用来存放每个客户端对应的MyWebSocket对象。*/
    private static ConcurrentHashMap<String,WebSocketServer> webSocketMap = new ConcurrentHashMap<>();
    /**与某个客户端的连接会话，需要通过它来给客户端发送数据*/
    private Session session;
    /**接收userId*/
    private String userId;

    private static List<String> list=new ArrayList<>();

    /**
     * 连接建立成功调用的方法*/
    @OnOpen
    public void onOpen(Session session,@PathParam("code") String code) throws IOException {

        if(!code.equals("xiaobaibaibubai")){
            log.error("参数验证失败,关闭会话");
            session.close();//验证失败关闭会话
            return;
        }

        this.session = session;
        InetSocketAddress remoteAddress = getRemoteAddress(session);
        this.userId=remoteAddress.getHostString();
        log.info("获取用户ip:"+this.userId);
        if(webSocketMap.containsKey(userId)){
            try {
                if(webSocketMap.get(userId).session!=null) {
                    return;
//                    webSocketMap.get(userId).session.close();//关闭对应的
                }
            }catch (Exception e){
                log.info("关闭webStock失败:"+e.getMessage());
            }
            webSocketMap.remove(userId);
            webSocketMap.put(userId,this);
            //加入set中
        }else{
            webSocketMap.put(userId,this);
            //加入set中
            addOnlineCount();
            //在线数加1
        }

        log.info("用户连接:"+userId+",当前在线人数为:" + getOnlineCount());

        try {
            sendMessage("连接成功");
        } catch (IOException e) {
            log.error("用户:"+userId+",网络异常!!!!!!");
        }
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() throws IOException {
        log.info("开始清空连接,当前在线用户数:"+webSocketMap.size());
        for(String str:webSocketMap.keySet()){
            if(webSocketMap.get(str)!=null) {
                webSocketMap.get(str).session.close();//关闭
                webSocketMap.remove(str);
                subOnlineCount();
            }
        }
        log.info("当前在线人数:"+webSocketMap.size()+",已经清空连接");
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息*/
    @OnMessage
    public void onMessage(String message) {
        log.info("已经接收到了用户消息:"+userId+",报文:"+message);
        if(list.size()!=0){
            list.forEach(l->{
                try {
                    sendMessage(l);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            });
            list.clear();
        }
    }

    /**
     *
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error) {
        log.error("用户错误:"+this.userId+",原因:"+error.getMessage());
        error.printStackTrace();
    }
    /**
     * 实现服务器主动推送
     */
    public void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
    }


    //新订单
    public static void sendNewOrderTip() throws IOException {
        if(webSocketMap.keySet().size()==0) {
            SmsUnit.sendOrderStatus("有新的订单啦");
            list.add("newOrder");
        }
        else
            for(String str:webSocketMap.keySet()){
                webSocketMap.get(str).sendMessage("newOrder");
            }
    }

    //申请取消
    public static void sendCancelOrderTip() throws IOException {
        if(webSocketMap.keySet().size()==0) {
            SmsUnit.sendOrderStatus("有用户取消订单了");
            list.add("cancelOrder");
        }
        else
            for(String str:webSocketMap.keySet()){
                webSocketMap.get(str).sendMessage("cancelOrder");
            }
    }

    //申请退款
    public static void sendReturnOrderTip() throws IOException {
        if(webSocketMap.keySet().size()==0) {
            SmsUnit.sendOrderStatus("有用户申请退款了");
            list.add("returnOrder");
        }
        else
            for(String str:webSocketMap.keySet()){
                webSocketMap.get(str).sendMessage("returnOrder");
            }
    }

    public static synchronized int getOnlineCount() {
        return onlineCount;
    }

    public static synchronized void addOnlineCount() {
        WebSocketServer.onlineCount++;
    }

    public static synchronized void subOnlineCount() {
        WebSocketServer.onlineCount--;
    }

    public static InetSocketAddress getRemoteAddress(Session session) {
        if (session == null) {
            return null;
        }
        RemoteEndpoint.Async async = session.getAsyncRemote();

        //在Tomcat 8.0.x版本有效
//		InetSocketAddress addr = (InetSocketAddress) getFieldInstance(async,"base#sos#socketWrapper#socket#sc#remoteAddress");
        //在Tomcat 8.5以上版本有效
        InetSocketAddress addr = (InetSocketAddress) getFieldInstance(async,"base#socketWrapper#socket#sc#remoteAddress");
        return addr;
    }

    private static Object getFieldInstance(Object obj, String fieldPath) {
        String fields[] = fieldPath.split("#");
        for (String field : fields) {
            obj = getField(obj, obj.getClass(), field);
            if (obj == null) {
                return null;
            }
        }

        return obj;
    }

    private static Object getField(Object obj, Class<?> clazz, String fieldName) {
        for (; clazz != Object.class; clazz = clazz.getSuperclass()) {
            try {
                Field field;
                field = clazz.getDeclaredField(fieldName);
                field.setAccessible(true);
                return field.get(obj);
            } catch (Exception e) {
            }
        }

        return null;
    }
}
